package com.yanyun.yczyy.api.repository.impl;

import com.yanyun.yczyy.api.entities.TblIOData;
import com.yanyun.yczyy.api.repository.IElevatorDataRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Slf4j
@Repository
public class ElevatorDataRepository implements IElevatorDataRepository {
    public ElevatorDataRepository(JdbcTemplate yczyy) {
        this.yczyy = yczyy;
    }

    @Override
    public TblIOData LastElevatorData() {
        final String sql = "select a.resource_name,a.io_time,a.`value` from tbl_io_data a,( select distinct device_id,max(io_time) io_time from tbl_io_data where io_time >= DATE_ADD(now(),interval -1 MINUTE) and sys_name = '电梯系统' and device_name = '门诊楼A9电梯' and resource_name ='门诊楼A9电梯楼层显示' and value = 5.00 and  resource_id <> 31822 group by device_id) b where a.device_id = b.device_id and a.io_time = b.io_time";
        try {
            return yczyy.queryForObject(sql, mapper);
        } catch (EmptyResultDataAccessException e) {
            return null;
        } catch (Exception e) {
            log.error("", e);
            return null;
        }
    }

    private final RowMapper<TblIOData> mapper = new BeanPropertyRowMapper<>(TblIOData.class);
    private final JdbcTemplate yczyy;
}
